<?php

namespace api\modules\v1\controllers;

use common\helpers\RegularHelper;
use common\models\common\AuthAssignment;
use Yii;
use yii\web\NotFoundHttpException;
use common\helpers\ResultDataHelper;
use common\helpers\ArrayHelper;
use common\models\member\Member;
use api\modules\v1\forms\UpPwdForm;
use api\controllers\OnAuthController;
use api\modules\v1\forms\LoginForm;
use api\modules\v1\forms\UpMobileForm;
use api\modules\v1\forms\MobileLogin;
use api\modules\v1\forms\SmsCodeForm;
use api\modules\v1\forms\RegisterForm;

/**
 * 登录接口
 *
 * Class SiteController
 * @package api\modules\v1\controllers
 * @author jianyan74 <751393839@qq.com>
 */
class SiteController extends OnAuthController
{
    public $modelClass = '';

    /**
     * 不用进行登录验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $optional = ['login-phone', 'login-name', 'refresh', 'login-mobile', 'sms-code', 'register', 'up-pwd', 'up-mobile'];

    /**
     * 手机号码登录
     * @return array|bool
     * @throws NotFoundHttpException
     * @throws \yii\base\Exception
     */
    public function actionLoginPhone()
    {
        $model             = new LoginForm();
        $model->attributes = Yii::$app->request->post();
        if (!RegularHelper::verify('mobile', $model->username)) {
            return ResultDataHelper::api(422, '手机格式不正确');
        }

        //查询用户是否存在
        $user = Member::find()
            ->where(['=', 'mobile', $model->username])
            ->one();
        if (empty($user)) {
            return ResultDataHelper::api(422, '账号或密码错误');
        }

        //生成用户资产
        \addons\TfFutures\common\models\Member::member($user->id);
        $model->username = $user->username;
        if ($model->validate()) {
            return Yii::$app->services->apiAccessToken->getAccessToken($model->getUser(),
                $model->group);
        }

        // 返回数据验证失败
        return ResultDataHelper::api(422, $this->getError($model));
    }

    /**
     * 用户名登录
     * @return array|bool
     * @throws NotFoundHttpException
     * @throws \yii\base\Exception
     */
    public function actionLoginName()
    {
        //根据用户名登录
        $model             = new LoginForm();
        $model->attributes = Yii::$app->request->post();
        $user = Member::find()
            ->where(['=', 'username', $model->username])
            ->one();
        if (empty($user)) {
            return ResultDataHelper::api(422, '用户名错误或密码错误');
        }
        if($user->status == 0) {
            return ResultDataHelper::api(422, '已被禁止登陆');
        } elseif ($user->status == -1) {
            return ResultDataHelper::api(422, '此用户已被删除');
        }
        //用户资产
        \addons\TfFutures\common\models\Member::member($user->id);
        $model->username = $user->username;
        if ($model->validate()) {
            return Yii::$app->services->apiAccessToken->getAccessToken($model->getUser(),
                $model->group);
        }

        // 返回数据验证失败
        return ResultDataHelper::api(422, $this->getError($model));
    }

    /**
     * 手机验证码登录Demo
     *
     * @return array|mixed
     * @throws \yii\base\Exception
     */
    private function actionLoginMobile()
    {
        $model             = new MobileLogin();
        $model->attributes = Yii::$app->request->post();
        if ($model->validate()) {
            return Yii::$app->services->apiAccessToken->getAccessToken($model->getUser(),
                $model->group);
        }

        // 返回数据验证失败
        return ResultDataHelper::api(422, $this->getError($model));
    }

    /**
     * 获取验证码
     *
     * @return int|mixed
     * @throws \yii\web\UnprocessableEntityHttpException
     */
    private function actionSmsCode()
    {
        $model = new SmsCodeForm();
        $model->attributes = Yii::$app->request->post();
        if (!$model->validate()) {
            return ResultDataHelper::api(422, $this->getError($model));
        }

        return $model->send();
    }

    /**
     * 注册
     *
     * @return array|mixed
     * @throws \yii\base\Exception
     */
    public function actionRegister()
    {
        $model             = new RegisterForm();
        $model->attributes = Yii::$app->request->post();
        if (!$model->validate()) {
            return ResultDataHelper::api(422, $this->analyErr($model->getFirstErrors()));
        }
        $member             = new Member();
        $member->attributes = ArrayHelper::toArray($model);
        $yq = Member::findOne($member->pid);    //查询是否有该邀请人账号
        if (empty($yq)) {
            return ResultDataHelper::api(422, '邀请人不存在');
        }
        //查询该用户名是否被占用
        if (Member::findOne(['username'=>$member->username])) {
            return ResultDataHelper::api(422, '该用户名已经被占用');
        }

        //查询此用户的代理，不存在的话则为其随机分配一个代理
        if ($yq->daili == ''){
            $isLevel = AuthAssignment::find()
                ->select('user_id')
                ->where(['role_id' => '4'])
                ->asArray()
                ->one();
            $member->daili         = $isLevel['user_id'];
        }else{
            $member->daili         = $yq->daili;
        }

        $member->username      = $model->username;     // 将用户注册的手机号赋值给用户名
        $member->password_hash = Yii::$app->security->generatePasswordHash($model->password);   //密码加密
        if (!$member->save()) {
            return ResultDataHelper::api(422, $this->analyErr($member->getFirstErrors()));
        }
        return Yii::$app->services->apiAccessToken->getAccessToken($member, $model->group);
    }

    /*
     * 修改手机号
     * */
    public function actionUpMobile()
    {
        if (!Yii::$app->request->isPost) {
            return ResultDataHelper::api(403, 'Access done');
        }
        $model             = new UpMobileForm();

        $model->attributes = Yii::$app->request->post();
        if (!$model->validate()) {
            return ResultDataHelper::api(422, $this->analyErr($model->getFirstErrors()));
        }
        $member           = $model->getUser();


        $member->mobile   = $model->mobile;
        $member->username = $model->mobile;
        $member->email    = $model->mobile;
        if (!$member->save()) {
            return ResultDataHelper::api(422, $this->analyErr($member->getFirstErrors()));
        }

        return Yii::$app->services->apiAccessToken->getAccessToken($member, $model->group);
    }


    /**
     * 密码重置
     *
     * @return array|mixed
     * @throws \yii\base\Exception
     */
    public function actionUpPwd()
    {
        if (!Yii::$app->request->isPost) {
            return ResultDataHelper::api(403, 'Access done');
        }
        $model             = new UpPwdForm();
        $model->attributes = Yii::$app->request->post();
        if($model->password_repetition !=$model->password){
            return ResultDataHelper::api(422, '两次密码不一致');
        }
        //获取到用户名进行验证
        if (!$model->validate()) {
            return ResultDataHelper::api(422, $this->analyErr($model->getFirstErrors()));
        }
        //$member                = $model->getUser();
        $member                = Member::findOne(Yii::$app->user->identity->member_id);
        if (empty($member)) {
            return ResultDataHelper::api(422, '用户不存在或该账号已被禁用');
        }
        $member->password_hash = Yii::$app->security->generatePasswordHash($model->password);

        if (!$member->save()) {
            return ResultDataHelper::api(422, $this->analyErr($member->getFirstErrors()));
        }
        return ResultDataHelper::api(200,'密码修改成功');

//        return Yii::$app->services->apiAccessToken->getAccessToken($member, $model->group);
    }

    /**
     * 权限验证
     *
     * @param string $action 当前的方法
     * @param null $model 当前的模型类
     * @param array $params $_GET变量
     * @throws \yii\web\BadRequestHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        // 方法名称
        if (in_array($action, ['index', 'view', 'update', 'create', 'delete'])) {
            throw new \yii\web\BadRequestHttpException('权限不足');
        }
    }
}
